﻿using HelperFromTheSkeleton.Common.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace HelperFromTheSkeleton.Common
{
    public class Config
    {
        private static IServiceProvider? _serviceProvider;

        private static JsonNode? _baseCommonConfigJson;
        private static JsonNode? _BaseCommonConfigJson
        {
            get
            {
                if (_baseCommonConfigJson == null)
                {
                    var basePath = AppDomain.CurrentDomain.BaseDirectory;
                    var baseCommonConfigPath = Path.Combine(basePath, "BaseCommonConfig.json");
                    var _baseCommonConfigText = File.ReadAllText(baseCommonConfigPath);
                    _baseCommonConfigJson = JsonNode.Parse(_baseCommonConfigText);
                }
                return _baseCommonConfigJson;
            }
        }
        private static ILoggerFactory? _loggerFactory;

        public void Init(IServiceProvider serviceDescriptors, string applicationName, string applicationCode)
        {
            _serviceProvider = serviceDescriptors;
            _loggerFactory = _serviceProvider.GetService<ILoggerFactory>();
            ApplicationCode = applicationCode;
            ApplicationName = applicationName;
        }

        /// <summary>
        /// 应用Code
        /// </summary>
        public static string ApplicationCode { get; set; } = string.Empty;

        /// <summary>
        /// 应用名称
        /// </summary>
        public static string ApplicationName { get; set; } = string.Empty;

        public static T? GetServer<T>()
        {
            if (_serviceProvider == null)
            {
                throw new InvalidOperationException("ServiceProvider是空的");
            }
            return _serviceProvider.GetService<T>();
        }

        public static List<T> GetServers<T>()
        {
            if (_serviceProvider == null)
            {
                throw new InvalidOperationException("ServiceProvider是空的");
            }
            return _serviceProvider.GetServices<T>().ToList();
        }

        public static List<T> GetServers<T>(IServiceScope serviceScope)
        {
            return serviceScope.ServiceProvider.GetServices<T>().ToList();
        }

        public static object? GetServer(Type baseType, Type type)
        {
            if (_serviceProvider == null)
            {
                throw new InvalidOperationException("ServiceProvider是空的");
            }
            return _serviceProvider.GetServices(baseType)?.FirstOrDefault(m => m?.GetType().FullName == type.FullName);
        }

        public static object? GetServer(IServiceScope serviceScope,Type baseType, Type type)
        {
            return serviceScope.ServiceProvider.GetServices(baseType)?.FirstOrDefault(m => m?.GetType().FullName == type.FullName);
        }

        public static IServiceScope GetScope()
        {
            if (_serviceProvider == null)
            {
                throw new InvalidOperationException("ServiceProvider是空的");
            }
            IServiceScope scope = _serviceProvider.CreateScope();
            return scope;
        }

        public static T? GetServer<T>(IServiceScope serviceScope)
        {
            return serviceScope.ServiceProvider.GetService<T>();
        }

        private static string? _issuerSigningKey;
        public static string IssuerSigningKey
        {
            get
            {
                if (!string.IsNullOrWhiteSpace(_issuerSigningKey))
                {
                    return _issuerSigningKey;
                }
                else
                {
                    if (_BaseCommonConfigJson == null) throw new Exception("基础配置为空");
                    _issuerSigningKey = _BaseCommonConfigJson?[nameof(IssuerSigningKey)]?.GetValue<string>();
                    return _issuerSigningKey ?? "";
                }
            }
        }

        private static TokenValidationParameters _tokenValidationParametersParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "TrPlatform",
            ValidateAudience = true,
            ValidAudience = "TrPlatform",
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(IssuerSigningKey))
        };

        public static TokenValidationParameters TokenValidationParametersParameters
        {
            get
            {
                return _tokenValidationParametersParameters;
            }
        }


        private static LogDBConnectionModel? _logDBConnectionConfig;

        public static LogDBConnectionModel? LogDBConnectionConfig
        {
            get
            {
                if (_logDBConnectionConfig != null)
                {
                    return _logDBConnectionConfig;
                }
                else
                {
                    if (_BaseCommonConfigJson == null) throw new Exception("基础配置为空");
                    _logDBConnectionConfig = JsonSerializer.Deserialize<LogDBConnectionModel>(_BaseCommonConfigJson?[nameof(LogDBConnectionConfig)]);
                    return _logDBConnectionConfig;
                }
            }
        }


        /// <summary>
        /// 日志
        /// </summary>
        /// <returns></returns>
        public static void Log(string text)
        {
            var _logger = _loggerFactory?.CreateLogger("Conventional");
            _logger?.LogInformation(text);
        }
    }
}